package com.wangzeqi.neihanduanzi.news.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.wangzeqi.neihanduanzi.base.BaseActivity;
import com.wangzeqi.neihanduanzi.R;
import com.wangzeqi.neihanduanzi.discovery.DiscoveryActivity;

import com.wangzeqi.neihanduanzi.enter.EnterPersonActivity;
import com.wangzeqi.neihanduanzi.home.HomeActivity;
import com.wangzeqi.neihanduanzi.msg.MsgActivity;
import com.wangzeqi.neihanduanzi.news.base.Base;
import com.wangzeqi.neihanduanzi.news.adapter.NewsAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by dllo on 16/1/7.
 */
public class NewsActivity extends BaseActivity implements View.OnClickListener {

    private ImageButton imageButton;
    private ImageButton image;
    private int a = 40;
    private List<Base.T1348647909107> base1;
    private String[] titles;
    private ArrayList<NetworkImageView> images;
    private ArrayList<View> dots;
    private TextView title;
    private ViewPager viewPager;
    private ViewPagerAdapter adapters;
    private int oldPosition = 0;
    private int currentItem;
    private ScheduledExecutorService scheduledExecutorService;
    private ListView listView;
    private NewsAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Base base;
    private static final String TAG = "NewsHeadLine";
    private RequestQueue queue;
    private String url = "http://c.3g.163.com/nc/article/headline/T1348647909107/0-20.html?from=tou" +
            "tiao&size=20&passport=&devId=X9N%2FozweCGhM6Gm2MRkxdQ%3D%3D&lat=5DhO6gePcR%2FxRxmn8Orw9A%3D" +
            "%3D&lon=f%2BHSkpT%2Bgq%2F6UGR9an2OIg%3D%3D&version=5.4.6&net=wifi&ts=1452669267&s" +
            "ign=HhRjgfItyulhosRXEqMNmh1jWGvoj5pH%2B%2BEkHc%2FvvSF48ErR02zJ6%2FKXOnxX046I&encryption=1&ca" +
            "nal=meizu_store2014_news";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_activity);
        findViewById(R.id.rl_home_btn).setOnClickListener(this);
        findViewById(R.id.rl_discovery_btn).setOnClickListener(this);
        findViewById(R.id.rl_review_btn).setOnClickListener(this);
        findViewById(R.id.rl_msg_btn).setOnClickListener(this);
        image = (ImageButton) findViewById(R.id.news_btn);
        imageButton = (ImageButton) findViewById(R.id.review_top_left_ib);
        imageButton.setOnClickListener(this);
        image.setOnClickListener(this);


        /** 设置旋转动画 */
        final RotateAnimation animation =new RotateAnimation(0f,359f,Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF,0.5f);
        animation.setDuration(500);//设置动画持续时间
        animation.setRepeatCount(1000);
        image.setAnimation(animation);
        animation.startNow();
        animation.cancel();

        View view1 = LayoutInflater.from(this).inflate(R.layout.headline_head, null);
        queue = Volley.newRequestQueue(this);
        listView = (ListView) findViewById(R.id.headlinelistview);
        adapter = new NewsAdapter(this);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_orange_light, android.R.color.holo_orange_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(NewsActivity.this, "刷新完成", Toast.LENGTH_SHORT).show();
                        get(url);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 3000);
            }
        });
        listView.addHeaderView(view1);
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                switch (i) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE://当不迁移转变时
                        //断定迁移转变到底部
                        if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1)) {
                            Toast.makeText(NewsActivity.this,"正在加载", Toast.LENGTH_SHORT).show();
                            String url1 = "http://c.3g.163.com/nc/article/list/T1348647909107/" + String.valueOf(a) + "-20.html";
                            a += 20;
                            StringRequest request = new StringRequest(url1, new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Gson gson = new Gson();
                                    response = response.replace(response.substring(3, 16), "1348647909107");
                                    Log.d(TAG, response);
                                    Base base2 = null;
                                    base2 = gson.fromJson(response, Base.class);

                                    try
                                    {
                                        base1.addAll(base2.getT1348647909107());
                                    }
                                    catch(Exception ex)
                                    {
                                      return;
                                    }

                                    base1.addAll(base2.getT1348647909107());
                                    adapter.getBase(base1);
                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                }
                            });
                            queue.add(request);
                        }
                        break;
                }
            }
            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        });

        dots = new ArrayList<View>();
        dots.add(view1.findViewById(R.id.dot_0));
        dots.add(view1.findViewById(R.id.dot_1));
        dots.add(view1.findViewById(R.id.dot_2));
        dots.add(view1.findViewById(R.id.dot_3));
        title = (TextView) findViewById(R.id.titles);
        viewPager = (ViewPager)findViewById(R.id.vp);
        base = new Base();
        get(url);
    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rl_home_btn:
                Intent intentHome = new Intent(this, HomeActivity.class);
                startActivity(intentHome);
                finish();
                break;
            case R.id.rl_discovery_btn:
                Intent intentDiscovery = new Intent(this, DiscoveryActivity.class);
                startActivity(intentDiscovery);
                finish();
                break;
            case R.id.rl_review_btn:
                Intent intentReview = new Intent(this, NewsActivity.class);
                startActivity(intentReview);
                break;
            case R.id.rl_msg_btn:
                Intent intentMsg = new Intent(this, MsgActivity.class);
                startActivity(intentMsg);
                finish();
                break;
            case R.id.review_top_left_ib:
                Intent intent = new Intent(this, EnterPersonActivity.class);
                startActivity(intent);
                break;
        }
    }
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
/**
 * Created by dllo on 16/1/11.
 */
    public void get(String url) {
        StringRequest request = new StringRequest(url, new ResponseListener(), new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }
    public class ResponseListener implements Response.Listener<String> {
        @Override
        public void onResponse(String response) {
            base1 = new ArrayList<>();
            Gson gson = new Gson();
            base = gson.fromJson(response, Base.class);
            //  adapter = new HeadLineListViewAdapter(getActivity(), base.getT1348647909107());
            base1 = base.getT1348647909107();
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    String url = base1.get(i - 1).getDocid();
                    if (url.contains("|")) {
                        url = url.substring(url.lastIndexOf("|") - 4, url.length());
                        Intent intent = new Intent(NewsActivity.this, NewsRootCombinnationActivity.class);
                        intent.putExtra("combination", url);
                        startActivity(intent);
                    } else if (base1.get(i - 1).getTag() != null) {


                    } else {
                        Intent intent = new Intent(NewsActivity.this, NewsRootTextActivity.class);
                        intent.putExtra("text", url);
                        startActivity(intent);
                    }

                }
            });

            adapter.setBase1(base1);
            // listView.setAdapter(adapter);
            /*********************************轮播图****************************************/

            titles = new String[]{
                    base1.get(0).getAds().get(0).getTitle(),
                    base1.get(0).getAds().get(1).getTitle(),
                    base1.get(0).getAds().get(2).getTitle(),
                    base1.get(0).getAds().get(3).getTitle(),
            };
            images = new ArrayList<NetworkImageView>();
            queue = Volley.newRequestQueue(NewsActivity.this);
            for (int i = 0; i < titles.length; i++) {
                String url = base1.get(0).getAds().get(i).getImgsrc();
                NetworkImageView imageView = new NetworkImageView(NewsActivity.this);
                imageView.setDefaultImageResId(R.mipmap.ugc_tip_loading_essay);
                imageView.setErrorImageResId(R.mipmap.ugc_tip_no_connection);
                final ImageLoader imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache() {
                    @Override
                    public Bitmap getBitmap(String url) {
                        return null;
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                    }
                });
                imageView.setImageUrl(url, imageLoader);
                images.add(imageView);
            }

            title.setText(titles[0]);
            adapters = new ViewPagerAdapter();


            viewPager.setAdapter(adapters);//绑定适配器
            viewPager.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {

                    return false;
                }
            });
            viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


                @Override
                public void onPageSelected(int position) {


                    // TODO Auto-generated method stub
                    title.setText(titles[position]);

                    dots.get(oldPosition).setBackgroundResource(R.drawable.kuang);
                    dots.get(position).setBackgroundResource(R.mipmap.account_icon_mobile);

                    oldPosition = position;
                    currentItem = position;
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });


            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

            //每隔2秒钟切换一张图片
            scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 3, 3, TimeUnit.SECONDS);

        }
    }

    private class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return images.size();
        }

        //是否是同一张图片
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            view.removeView(images.get(position));

        }

        @Override
        public Object instantiateItem(ViewGroup view, final int position) {
            // TODO Auto-generated method stub
            view.addView(images.get(position));
            images.get(position).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String url = base1.get(0).getAds().get(position).getUrl();
                    url = url.substring(url.lastIndexOf("|") - 4, url.length());
                    Intent intent = new Intent(NewsActivity.this,NewsRootCombinnationActivity.class);
                    intent.putExtra("combination", url);
                    startActivity(intent);
                }
            });

            return images.get(position);
        }
    }

    @Override
    public void onStart() {

        super.onStart();

//        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
//
//        //每隔2秒钟切换一张图片
//        scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 3, 3, TimeUnit.SECONDS);
    }

    //切换图片
    private class ViewPagerTask implements Runnable {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            currentItem = (currentItem + 1) % titles.length;
            //更新界面
            handler.obtainMessage().sendToTarget();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //设置当前页面
            viewPager.setCurrentItem(currentItem);
        }
    };

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }


}

